package com.example.bookexchange;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class AddAddressActivity extends AppCompatActivity {

    private EditText etContactName, etContactPhone, etDetailedAddress;
    private Spinner spinnerProvince, spinnerCity, spinnerDistrict;
    private Button btnSubmitAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);

        // 初始化视图
        etContactName = findViewById(R.id.etContactName);
        etContactPhone = findViewById(R.id.etContactPhone);
        etDetailedAddress = findViewById(R.id.etDetailedAddress);
        spinnerProvince = findViewById(R.id.spinnerProvince);
        spinnerCity = findViewById(R.id.spinnerCity);
        spinnerDistrict = findViewById(R.id.spinnerDistrict);
        btnSubmitAddress = findViewById(R.id.btnSubmitAddress);

        // 设置下拉菜单
        setupSpinners();

        // 提交按钮点击事件
        btnSubmitAddress.setOnClickListener(v -> submitAddress());
    }

    private void setupSpinners() {
        // 设置省份适配器
        ArrayAdapter<CharSequence> provinceAdapter = ArrayAdapter.createFromResource(
                this, R.array.provinces, android.R.layout.simple_spinner_item);
        provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerProvince.setAdapter(provinceAdapter);

        // 省份选择事件
        spinnerProvince.setOnItemSelectedListener(new ProvinceSelectedListener(this, spinnerCity, spinnerDistrict));

        // 城市选择事件
        spinnerCity.setOnItemSelectedListener(new CitySelectedListener(this, spinnerDistrict));
    }

    private void submitAddress() {
        // 获取用户输入的数据
        String contactName = etContactName.getText().toString().trim();
        String contactPhone = etContactPhone.getText().toString().trim();
        String detailedAddress = etDetailedAddress.getText().toString().trim();
        String province = spinnerProvince.getSelectedItem().toString();
        String city = spinnerCity.getSelectedItem().toString();
        String district = spinnerDistrict.getSelectedItem().toString();

        // 验证输入数据
        if (contactName.isEmpty() || contactPhone.isEmpty() || detailedAddress.isEmpty() ||
                province.equals("请选择省") || city.equals("请选择市") || district.equals("请选择区")) {
            Toast.makeText(this, "请填写完整的地址信息", Toast.LENGTH_SHORT).show();
            return;
        }

        // 拼接完整地址
        String fullAddress = province + " " + city + " " + district + " " + detailedAddress;

        // 保存地址（可扩展为存储到数据库或返回给调用页面）
        Toast.makeText(this, "地址已保存:\n" + fullAddress, Toast.LENGTH_SHORT).show();

        // 返回上一页
        finish();
    }
}
